﻿using MediatR;
using Yuekao.API.Read.Command;
using Yuekao.Domain.API;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.Entitys;

namespace Yuekao.API.Read.CommandHandler
{
    public class WorkflowInstanceShowCommandHandler : IRequestHandler<WorkflowInstanceShowCommand, APIResult<APIPagging<WorkflowInstanceModel>>>
    {
        private readonly IBaseRepository<WorkflowInstanceModel> _repository;
        public WorkflowInstanceShowCommandHandler(IBaseRepository<WorkflowInstanceModel> repository)
        {
            _repository = repository;
        }
        public Task<APIResult<APIPagging<WorkflowInstanceModel>>> Handle(WorkflowInstanceShowCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPagging<WorkflowInstanceModel>> result = new APIResult<APIPagging<WorkflowInstanceModel>>();
            result.Code = APIEnum.Success;
            result.Message = "流程实例列表显示成功";
            var list = _repository.GetAll();
            var totaCount = list.Count();
            var pageCount = (int)Math.Ceiling(totaCount * 1.0 / request.pageSize);
            APIPagging<WorkflowInstanceModel> pagging = new APIPagging<WorkflowInstanceModel>();
            pagging.TotaCount = totaCount;
            pagging.PageCount = pageCount;
            pagging.PageData = list.OrderByDescending(x => x.CompeltaTime).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            result.Data = pagging;
            return Task.FromResult(result);
        }
    }
}
